package com.example.service.impl;

import com.example.domain.Comment;
import com.example.dao.CommentMapper;
import com.example.service.CommentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class CommentServiceImpl implements CommentService {

    @Autowired
    private CommentMapper commentMapper;

    @Override
    public List<Comment> getCommentsByPostId(Integer postId) {
        // 获取所有评论
        List<Comment> allComments = commentMapper.findByPostId(postId);

        // 构建层级结构
        return buildCommentTree(allComments);
    }

    /**
     * 构建评论树形结构
     */
    private List<Comment> buildCommentTree(List<Comment> allComments) {
        List<Comment> rootComments = new ArrayList<>();
        Map<Integer, Comment> commentMap = new HashMap<>();

        // 将所有评论放入Map中，便于查找，并初始化replies列表
        for (Comment comment : allComments) {
            comment.setReplies(new ArrayList<>());
            commentMap.put(comment.getId(), comment);
        }

        // 构建树形结构
        for (Comment comment : allComments) {
            if (comment.getParentId() == null || comment.getParentId() == 0) {
                // 根评论（顶级评论）
                rootComments.add(comment);
            } else {
                // 子评论，找到父评论并添加到其replies中
                Comment parent = commentMap.get(comment.getParentId());
                if (parent != null) {
                    parent.getReplies().add(comment);
                } else {
                    // 如果找不到父评论，作为根评论处理
                    rootComments.add(comment);
                }
            }
        }

        return rootComments;
    }

    @Override
    public List<Comment> getRepliesByParentId(Integer parentId) {
        return commentMapper.findByParentId(parentId);
    }

    @Override
    public void save(Comment comment) {
        commentMapper.save(comment);
    }

    @Override
    public void update(Comment comment) {
        commentMapper.update(comment);
    }

    @Override
    public void updateStatus(Integer id, String status) {
        commentMapper.updateStatus(id, status);
    }

    @Override
    public Comment findById(Integer id) {
        return commentMapper.findById(id);
    }

    @Override
    public List<Comment> findAll() {
        return commentMapper.findAll();
    }

    @Override
    public void delete(Integer id) {
        commentMapper.delete(id);
    }

    @Override
    public List<Comment> findByUserId(Integer userId) {
        return commentMapper.findByUserId(userId);
    }

    @Override
    public List<Comment> findAllForAdmin() {
        return commentMapper.findAllForAdmin();
    }

    @Override
    public int getCommentCountByPostId(Integer postId) {
        return commentMapper.getCommentCountByPostId(postId);
    }
}